from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from .models import OAuthQQUser
from oauth.utils import generic_openid_token
# Create your views here.
class QQAuthURLView(APIView):
    """提供QQ登录页面网址
    https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=xxx&redirect_uri=xxx&state=xxx
    1用户点击按钮的时候 ，前端发送一个ajax请求
    2前端获取url的请求
    3后端生成一个url
    """
    def get(self, request):

        state = '/'

        # 获取QQ登录页面网址 创建对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI, state=state)
        auth_url = oauth.get_qq_url()
        #生成url
        return Response({'auth_url':auth_url})
from rest_framework.mixins import CreateModelMixin
from rest_framework import status
from .serializers import QQAuthUserSerializer
class QQAuthUserView(APIView):
    """用户扫码登录的回调处理"""



    def get(self, request):
        # 提取code请求参数
        code = request.query_params.get('code')
        if code is None:
            return Response({'message':'缺少code'}, status=status.HTTP_400_BAD_REQUEST)

        # 创建工具对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                            redirect_uri=settings.QQ_REDIRECT_URI)
        #获取外界数据最好捕获异常
        try:
            # 使用code向QQ服务器请求access_token
            access_token = oauth.get_access_token(code)

            # 使用access_token向QQ服务器请求openid
            openid = oauth.get_open_id(access_token)
        except Exception:
            return Response({'message': 'QQ服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 使用openid查询该QQ用户是否在美多商城中绑定过用户
        try:
            qq_oauth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 如果openid没绑定美多商城用户，创建用户并绑定到openid
            # 为了能够在后续的绑定用户操作中前端可以使用openid，在这里将openid签名后响应给前端
            #敏感数据要处理
            openid_token = generic_openid_token(openid)
            return Response({'access_token':openid_token})
        else:
            from rest_framework_jwt.settings import api_settings
            # 如果openid已绑定美多商城用户，直接生成JWT token，并返回
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            #返回给我们一个字符串
            payload = jwt_payload_handler(qq_oauth_user.user)
            #我们要对字符串进行编码
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'user_id': qq_oauth_user.user.id,

            })

            return Response({'token':token,'user_id':qq_oauth_user.user.id})



    def post(self,request):

        #1.接受参数
        #2.对参数进行校验  --》序列化器
        serializer = QQAuthUserSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 3. 保存数据
        user = serializer.save()
        # 4. 返回响应

        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # jwt_payload_handler 的调用原理就是将user对象给 jwt，jwt会自动的获取指定的数据
        # 返回给我们一个字符串
        payload = jwt_payload_handler(user)
        # 我们需要对字符串进行编码
        token = jwt_encode_handler(payload)

        return Response({'token':token})



# class OauthQQBindView(APIView):
#
#
#     def post(self,request):
#         pass
#

#加密
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

#1.创建序列化器
# 参数1： 秘钥
# 参数2： 有效期（秒数）
s = Serializer('abc',3600)

#2.对敏感数据进行处理
dict = {
    'openid':123456
}

token = s.dumps(dict)

token.decode()


#解密
s = Serializer('abc',3600)

s.loads(token)



#有效期
s = Serializer('abc',1)
token = s.dumps(dict)

token.decode()

s.loads(token)
"""
'eyJleHAiOjE1Mzk0MDQzODUsImlhdCI6MTUzOTQwMDc4NSwiYWxnIjoiSFMyNTYifQ.
eyJvcGVuaWQiOjEyMzQ1Nn0.
thexnsg2igpctDkoS2aqHnZDafPOlnf2ho8wZ-qH7jA'
"""

